<template>
  <div class="dialog">
    <el-dialog
      title="图片上传"
      :visible.sync="imageFormVisible"
      :before-close="handleClose"
      width="700px"
    >
      <el-divider></el-divider>
      <el-form
        :model="formData"
        :rules="rules"
        ref="imageUpload"
        label-width="100px"
        label-position="right"
        size="small"
        style="width: 100%"
      >
        <el-form-item label="图片分类" prop="imageClassId">
          <el-select v-model="formData.imageClassId" placeholder="请选择">
            <el-option
              v-for="item in imageClass"
              :key="item.type"
              :label="item.item"
              :value="item.type"
              @change="selectImageClass"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="图片上传" class="image-box" prop="imageUrlList">
          <el-upload
            action="#"
            list-type="picture-card"
            accept=".jpg,.png"
            multiple
            :http-request="handleUploadImg"
            :file-list="imageList"
            :limit="limit"
            :before-upload="checkFile"
            :on-exceed="handleExceed"
            :on-change="selectFile"
            :on-remove="removeFile"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <div class="el-upload__tip">
			    	<p>1.建议图片像素1280×720（16:9）</p>
				    <p>2.图片格式 jpg,png</p>
				    <p>3.单张图片大小不超过2M</p>
				    <p>4.每次最多可以上传10张</p>
		      </div>
        </el-form-item>
        <!-- 进度条 -->
        <!-- <el-form-item>
          <div class="el-progress-grid">
            <el-progress
              class="el-progressbar"
              type="line"
              v-if="progressFlag"
              color="#67c23a"
              :percentage="progressPercent"
            >
            </el-progress>
          </div>
        </el-form-item> -->
        <el-form-item position="right">
          <el-button
            type="primary"
            @click="submitForm('imageUpload')"
            class="btnSave"
            >提交</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import upload from "./upload";
export default {
  name: "imageUpload",
  data() {
    return {
      imageFormVisible: false, //上传图片页面是否显示
      formData: {
        imageClassId: "",
        imageUrlList: "",
        carTypeId: "", //车型id
      },
      rules: {
        imageClassId: [
          { required: true, message: "请选择图片分类", trigger: "change" },
        ],
        imageUrlList: [
          { required: true, message: "请上传图片", trigger: "change" },
        ],
      },
      imageList: [], //图片文件列表
      imageClass: [], //图片分类
      limit: 10, //上传图片数量限制
    };
  },
  methods: {
    init(carTypeId) {
      if (carTypeId == undefined || carTypeId <= 0) {
        this.$message({
          type: "error",
          message: "车型不存在！",
        });
        return false;
      }
      this.imageFormVisible = true;
      this.formData.carTypeId = carTypeId;
    },
    submitForm(formName) {
      // console.log(this.formData);
      this.formData.imageUrlList = this.imageList.map((image) => {
        return image.imageUrl;
      });
      console.log(this.formData);
      //提交配置数据
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$http
            .post(
              `/admin/yt_car/index.php?act=yt_car&op=saveImageUrl`,
              this.formData
            )
            .then((res) => {
              // console.log(res);
              if (res.code == 1) {
				this.$emit('getDataList',this.formData.imageClassId)
                this.resetForm("imageUpload");
                this.imageFormVisible = false;
                this.$message({
                  type: "success",
                  message: "保存成功!",
                });
              }
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.imageList = [];
    },
    handleClose(close) {
      console.log(close);
      this.$confirm("关闭后数据不会保存！确认关闭？")
        .then((_) => {
          this.resetForm("imageUpload");
          close();
        })
        .catch((_) => {});
    },
    async handleUploadImg(file) {
      let rep = await upload(
        `/admin/yt_car/index.php?act=yt_car&op=uploadImage&brand_id=${this.formData.carTypeId}`,
        file
      );
      console.log(rep);
      if (rep.code === 200) {
        this.imageList.map((image) => {
          if (image.uid == file.file.uid) {
            image.imageUrl = rep.data.filename;
          }
        });
        console.log(this.imageList);
        console.log("Uploaded successfully", rep);
      }
    },
    //选择图片的回调
    selectFile(file, fileList) {
      this.imageList = fileList;
    },
    //删除图片的回调
    async removeFile(file, fileList) {
      this.imageList = fileList;
      console.log(this.imageList);
      let res = await this.$http.post(
        `/admin/yt_car/index.php?act=yt_car&op=deleteImage`,
        {
          id: this.formData.carTypeId,
          image_list: [file.imageUrl],
        }
      );
      // console.log(res);
      if (res.code == 1) {
        this.$message({
          type: "success",
          message: "删除成功!",
        });
      }
    },
    //上传前检查文件
    checkFile(file) {
      const isJPG = file.type === "image/jpeg";
      const isPng = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG && !isPng) {
        this.$message.error("上传图片只能是 JPG、PNG 格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
        return false;
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 ${this.limit} 个文件，还可以上传 ${
          this.limit - fileList.length
        } 个文件`
      );
    },
    //获取图片分类
    getImageItems() {
      this.$http
        .post(`/admin/yt_car/index.php?act=yt_car&op=getsItem`)
        .then((res) => {
          // console.log(res);
          if (res.code == 1) {
            this.imageClass = res.data;
          }
        });
    },
    //图片分类选择
    selectImageClass(val) {
      this.formData.imageClass = val;
    },
  },
  created() {
    //图片分类
    this.getImageItems();
  },
};
</script>

<style scoped lang="scss">
.el-dialog {
  .el-dialog__header {
    padding-bottom: 5px;
  }
  .el-dialog__body {
    padding: 10px 10px;
  }
  .el-divider--horizontal {
    margin-top: 0px;
  }
  .btnSave {
    float: right;
    margin-right: 15px;
    width: 88px;
  }
}
.image-box .el-form-item__content {
  min-height: 210px;
  max-height: 500px;
  overflow-y: auto;
  .el-form-item__error {
    position: relative;
    top: 0px;
  }
}
/deep/.el-upload--picture-card{
  height:84px;
  line-height: 92px;
}
</style>
